package Grantsfire::Controller::Auth;

use strict;
use warnings;
use parent 'Catalyst::Controller';

=head1 NAME

Grantsfire::Controller::Auth - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut


=head2 index 

=cut

sub index : Path :Args(0) { $_[1]->forward('do_login') }
sub logout : Local Args(0) { 
    my ( $self, $c ) = @_;
    $c->stash->{auth_user} = undef;
    $c->logout;
}

sub do_login : Local Args(0) {
    my ( $self, $c ) =  @_;
    my $data = $c->req->params;
    $c->session->{auth_caller} = $data->{caller} if $data->{caller};

    $c->res->status( 304 );
    my $uri = $c->req->uri;

    if ($c->authenticate( $data )) {
        $c->res->status( 304 );
        $uri = $c->uri_for($c->controller('Auth')->action_for('success'));
    } else {
        $uri = $c->uri_for($c->controller('Auth')->action_for('failed'));
    }
    $c->res->redirect( $uri );
}

sub success : Local Args(0) { 
    my ( $self, $c ) = @_;
    if ( $c->user_exists ) {
      my $user = $c->user;
      if ($c->user_in_realm('openid')) {
        my $identifier = $c->user->url;
        $user = $c->model('GF::User')->find_or_create({openid => $identifier});
        $user->display_name($c->user->display);
        $user->update;

      }
      
      $c->session->{auth_user} = $user;
      if ($c->session->{auth_caller}) {
        $c->res->redirect(delete $c->session->{auth_caller});
        $c->detach;
      }
    } else {
        $c->res->redirect( 
            $c->uri_for( $c->controller('Auth')->action_for('failed'))
        );
        $c->detach;
    }
}

sub failed : Local Args(0) { }


1;
